package com.tian.gateway.demos.web;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;

/**
 * @author zhumengping
 * @title: MyGatewayFilter
 * @projectName zhump-cloud
 * @date 2023/8/3 14:35
 */
@Log4j2
@Component
public class MyGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("......MyGatewayFilter start......");
        URI uri = exchange.getRequest().getURI();
        log.info("【MyGatewayFilter()】uri:{}",uri);
        HttpMethod method = exchange.getRequest().getMethod();
        log.info("【MyGatewayFilter()】method:{}",method);
        String methodValue = exchange.getRequest().getMethodValue();
        log.info("【MyGatewayFilter()】methodValue:{}",methodValue);
        RequestPath path = exchange.getRequest().getPath();
        log.info("【MyGatewayFilter()】path:{}",path.toString());
        InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
        log.info("【MyGatewayFilter()】remoteAddress:{}",remoteAddress.toString());

//        String token = exchange.getRequest().getQueryParams().getFirst("token");
//        if (StringUtils.isBlank(token)){
//            log.info("【MyGatewayFilter()】 token is empty");
//            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
//            return exchange.getResponse().setComplete();
//        }


        ServerHttpRequest token = exchange.getRequest().mutate().headers(httpHeaders -> {
            httpHeaders.set("token", "123456");
        }).build();

        return chain.filter(exchange.mutate().request(token.mutate().build()).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
